package com.hr.controller;

import com.hr.entity.News;
import com.hr.entity.Topic;
import com.hr.service.NewsService;
import com.hr.service.TopicService;
import com.hr.until.PageUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/*
    Created with IntelliJ IDEA.
    @author: wang sir
    Date: 2021/7/20
    Time: 10:19
    To change this template use File | Settings | File Templates.
    Description: 
 */
@Controller
@RequestMapping("/news/")
public class NewsController {
    @Autowired
    private NewsService newsService;
    @Autowired
    private TopicService topicService;
    @GetMapping("list")
    public String newList(Model model,Integer pageNo){
        if (pageNo==null){
            pageNo=1;
        }
        Page page= newsService.queryJpaPageNews(pageNo);
        model.addAttribute("page",page);
        return "admin/admin";
    }
    @GetMapping("/admin/pagenews")
    @ResponseBody
    public Object pageNews(@RequestParam(value = "pageNo",required = false) Integer pageNo){
        if (pageNo == null || pageNo<1){
            pageNo = 1;
        }
        PageUtil page = newsService.queryNewsByPage(pageNo);
        return page;

    }

    @GetMapping("toadd")
    public String toAdd(Model model){
        List<Topic> topics = topicService.quarryAllTopics();
        model.addAttribute("topics",topics);
        return "admin/news_add";
    }
    @PostMapping("doadd")
    public String doAdd(News news){
        News news1 = newsService.addNews(news);
        return "redirect:/news/list";
    }

    @GetMapping("toupdate")
    public String toUpdate(Long nid,Model model){
        News news = newsService.queryNewsByNid(nid);
        List<Topic> topics = topicService.quarryAllTopics();
        model.addAttribute("topics",topics);
        model.addAttribute("news",news);
        return "admin/news_modify";
    }
    @PostMapping("doupdate")
    public String doUpdate(News news){
        News news1 = newsService.updateNews(news);
        return "redirect:/news/list";
    }

    @GetMapping("delete")
    public String delete(Long nid){
        newsService.deleteNewsById(nid);
        return "redirect:/news/list";
    }

}